<?php
if ( !defined('IN_ADMINCP') || !defined('IN_SEC') ){
	exit('Access Denied.');
}

$call = conf('call-center');

$query_string = array();
$uri = $_SERVER['REQUEST_URI'];
$query = strpos($uri, '?');

if ( $query ){
	$uri = substr($uri, $query + 1);
	parse_str($uri, $query_string);
}

$companys = get_parse_companys();
$status = customer_status();
$demands = customer_demand();
$sources = customer_source();
$natures = customer_nature();
$jobs = customer_jobs();

$totalsearch = htmlspecialchars($_G['gp_totalsearch']);

$members = (limitquery('admincp_member', array('departmentid' => 3)));

$admins = array();
foreach( $members as $k => $v ){
	$admins[$v['id']] = array(
		'id' => $v['id'],
		'name' => heivrid($v)
	);
}

$adminid = &$admincp->adminid;

$searchby = $_G['gp_searchby'] ? $_G['gp_searchby'] : 'all';
$searchdate = $_G['gp_searchdate'] ? $_G['gp_searchdate'] : 'all';
$where = array(
//	'adminid' => $adminid
);

$group = $admincp->groups[$admincp->admin['groupid']];

$childrens_group_where = array(
	'parentid' => $group['id']
);

if( $group['rank'] >= 80 ){
	$childrens_group_where = array(
		'departmentid' => $group['departmentid'],
		"`rank` < {$group['rank']}",
	);
}

$childrens_groups = limitquery('admincp_group', $childrens_group_where);
$childrens_groupsids = idserialize($childrens_groups);

$childrens_where = array(
	"`groupid` IN('{$childrens_groupsids}')",
);
if( !$admincp->founder ){
	$childrens_where['companyid'] = $admincp->admin['companyid'];
}

$childrens = limitquery('admincp_member', $childrens_where);
$childrensids = idserialize($childrens);
if( $searchby == 'onlyme' ){
	$where['adminid'] = $adminid;
}if( $searchby == 'mychildren' ){
		if( !$admincp->founder ){
			if( $childrensids ){
				unset($where['adminid']);
				$where[] = "`adminid` IN('{$childrensids}')";
			}else{
				$where['adminid'] = 0;
			}
		}else{
			$where[] = "`adminid` != {$adminid}";
		}
}elseif( $searchby == 'pools' ){
	$where['adminid'] = 0;
}else if( $searchby == 'all' ){
	if( !$admincp->founder ){
		if( $childrensids ){
			$where[] = "`adminid` = {$adminid} OR `adminid` IN('{$childrensids}')";
		}else{
			$where['adminid'] = $adminid;
		}
	}
}
if( $searchdate == 'today' ){
	$begin_time = strtotime(date('Y-m-d'));
	$end_time = $begin_time + 86400;
}else if( $searchdate == 'week' ){
	$begin_time = strtotime("last Sunday +1 day");
	$end_time = strtotime("next Sunday");
}else if( $searchdate == 'month' ){
	$date = date('Y-m-d');
	$firstday = date('Y-m-01', strtotime($date));
	$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
	$begin_time = strtotime($firstday);
	$end_time = strtotime($lastday);
}else if( $searchdate == 'need_contact' ){
	$where['next_contact_time'] = strtotime(date('Y-m-d'));
}

if( $begin_time && $end_time ){
	$where[] = "`create_time` >= {$begin_time} AND `create_time` <= {$end_time}";
}

#==========Search
$sea_high = $_G['gp_sea_high'];

$sea_source = htmlspecialchars($_G['gp_source']);
$sea_nature = htmlspecialchars($_G['gp_nature']);
$sea_status = $_G['gp_status'] ? $_G['gp_status'] : -1;
$sea_demands = $_G['gp_demands'] ? $_G['gp_demands'] : array();

$sea_name = htmlspecialchars($_G['gp_name']);
$sea_contact_name = htmlspecialchars($_G['gp_contact_name']);
$sea_contact_phone = htmlspecialchars($_G['gp_contact_phone']);
$sea_contact_tel = htmlspecialchars($_G['gp_contact_tel']);
$sea_contact_email = htmlspecialchars($_G['gp_contact_email']);
$next_contact_time = $_G['gp_next_contact_time'] ? strtotime($_G['gp_next_contact_time']) : 0;

$sea_adminid = $_G['gp_sea_adminid'] > 0 ? intval($_G['gp_sea_adminid']) : 0;

if( $sea_source && $sea_source >= 0 ){
	$where['source'] = $sea_source;
}
if( $sea_nature && $sea_nature >= 0 ){
	$where['nature'] = $sea_nature;
}
if( $sea_status && $sea_status >= 0 ){
	$where['status'] = $sea_status;
}

if( $sea_demands ){
	$demands_keys = join('\',\'', $sea_demands);
	$customer_demands = limitquery('customer_demands', "`key` IN('{$demands_keys}')");
	$ids = idserialize($customer_demands, 'customerid');
	$where[] = "`id` IN('{$ids}')";
}

if( $sea_name ){
	$where[] = "`name` LIKE '%".DB::EscapeString($sea_name)."%'";
}

if( $sea_contact_name ){
	$where[] = "`contact_name` LIKE '%".DB::EscapeString($sea_contact_name)."%'";
}
if( $sea_contact_email ){
	$where[] = "`contact_email` LIKE '%".DB::EscapeString($sea_contact_email)."%'";
}
if( $sea_contact_phone ){
	$where[] = "`contact_phone` LIKE '%".DB::EscapeString($sea_contact_phone)."%'";
}
if( $sea_contact_tel ){
	$where[] = "`contact_tel` LIKE '%".DB::EscapeString($sea_contact_tel)."%'";
}

if( $next_contact_time ){
	$where['next_contact_time'] = $next_contact_time;
}

if( $sea_adminid > 0 ){
	$where['adminid'] = $sea_adminid;
}

if( $totalsearch ){
	$where[] = "`name` LIKE '%".DB::EscapeString($totalsearch)."%'
	 OR `address` LIKE '%".DB::EscapeString($totalsearch)."%'
	 OR `contact_name` LIKE '%".DB::EscapeString($totalsearch)."%'
	 OR `contact_tel` LIKE '%".DB::EscapeString($totalsearch)."%'
	 OR `contact_phone` LIKE '%".DB::EscapeString($totalsearch)."%'
	 OR `contact_email` LIKE '%".DB::EscapeString($totalsearch)."%'
	 ";
}
#Search==========
#ExportWhere=====
if( $_G['gp_export'] ){
	if( $_G['gp_export'] == 'all' ){
		$pagesize = 9999;
	}else{
		$exports = explode(',', $_G['gp_export']);
		$exportids = array();
		foreach( $exports as $k => $v ){
			if( is_numeric($v) ){
				$exportids[$v] = $v;
			}
		}
		$exportids = join('\',\'', $exportids);
		$where[] = "`id` IN ('{$exportids}')";
	}
}

$count = DB::Count('customer', $where);
$pages = pages($count, $pagesize ? $pagesize : 20);
$options = array('order' => 'ORDER BY `last_contact_time` DESC, `id` DESC');
$customers = limitquery('customer', $where, $options, $pages['offset'], $pages['pagesize']);

if( $_G['gp_export'] ){
	$keynames = array(
		'id' => 'ID',
		'creator' => '创建人',
		'admin' => '客户负责人',
		'name' => '客户名称',
		'status' => '客户状态',
		'nature' => '客户性质',
		'demands' => '需求意向',
		'url' => '客户网站',
		'province' => '省份',
		'city' => '城市',
		'address' => '地址',
		'contact_name' => '联系人姓名',
		'contact_job' => '联系人职位',
		'contact_tel' => '联系人固话',
		'contact_phone' => '联系人电话',
		'contact_email' => '联系人邮箱',
		'contact_qq' => '联系人QQ',
		'create_time' => '添加时间'
	);
	$loc_ids = idserializes($customers, 'province, city');
	$provinces = parse_array(limitquery('district', "`id` IN('{$loc_ids['province']}')"));
	$citys = parse_array(limitquery('district', "`id` IN('{$loc_ids['city']}')"));

	foreach( $customers as $k => $v ){
		$v['creator'] = heivrid($admincp->admins[$v['creatorid']]);
		$v['admin'] = $v['adminid'] ? heivrid($admincp->admins[$v['adminid']]) : '客户池';
		$v['status'] = $status[$v['status']];
		$v['nature'] = $natures[$v['nature']];
		$demands_data = json_decode($v['demands'], true);
		$demand = '';
		foreach( $demands_data as $d => $dv ){
			$demand .= ($demands[$d].',');
		}
		$demand = trim($demand, ',');
		$v['demands'] = $demand;
		$v['province'] = $provinces[$v['province']]['name'] ? $provinces[$v['province']]['name'] : '';
		$v['city'] = $citys[$v['city']]['name'] ? $citys[$v['city']]['name'] : '';
		$v['contact_job'] = $jobs[$v['contact_job']];
		$v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
		$customers[$k] = $v;
	}
	down_xls($customers, $keynames, '[Heivr Tech]黑晶CRM客户 - ' . date('YmdHis'));
}

function filter_by_type($name = '全部', $by = 'all'){
	global $searchby;

	$query_string = array();
	$uri = $_SERVER['REQUEST_URI'];
	$query = strpos($uri, '?');
	if ( $query ){
		$uri = substr($uri, $query + 1);
		parse_str($uri, $query_string);
	}
	if ( $query_string['page'] ){
		unset($query_string['page']);
	}
	$query_string['searchby'] = $by;

	$href = '?' . http_build_query($query_string);
	$class = $searchby == $by ? 'inverse' : 'primary';
	$name = $searchby == $by ? '<i class="icon-check"></i><strong>' . $name . '</strong>' : $name;
	return '<a class="btn btn-xs btn-'.$class.'" href="'.$href.'">'.$name.'</a>
';
}
function filter_by_date($name = '不限日期', $by = 'all'){
	global $searchdate;

	$query_string = array();
	$uri = $_SERVER['REQUEST_URI'];
	$query = strpos($uri, '?');
	if ( $query ){
		$uri = substr($uri, $query + 1);
		parse_str($uri, $query_string);
	}
	if ( $query_string['page'] ){
		unset($query_string['page']);
	}
	$query_string['searchdate'] = $by;

	$href = '?' . http_build_query($query_string);
	$class = $searchdate == $by ? 'inverse' : 'primary';
	$name = $searchdate == $by ? '<i class="icon-check"></i><strong>' . $name . '</strong>' : $name;
	return '<a class="btn btn-xs btn-'.$class.'" href="'.$href.'">'.$name.'</a>
';
}
?>